package cn.yedong.user.service.impl;

import cn.yedong.basic.dto.LoginDto;
import cn.yedong.basic.exception.BusinessException;
import cn.yedong.basic.jwt.JwtUtils;
import cn.yedong.basic.jwt.LoginData;
import cn.yedong.basic.jwt.RsaUtils;
import cn.yedong.basic.util.*;
import cn.yedong.system.domain.Menu;
import cn.yedong.user.constant.WxConstants;
import cn.yedong.user.domain.Logininfo;
import cn.yedong.user.domain.User;
import cn.yedong.user.domain.Wxuser;
import cn.yedong.user.mapper.LogininfoMapper;
import cn.yedong.user.mapper.UserMapper;
import cn.yedong.user.mapper.WxuserMapper;
import cn.yedong.user.service.ILogininfoService;
import cn.yedong.basic.service.impl.BaseServiceImpl;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.security.PrivateKey;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 没绑定wxuser——重新绑定
 * 绑定wxuser
 *      没注册user——重新绑定
 * 没有绑定wxuser
 *      没有user——注册logininfo；注册user；注册wxuser；
 *      有user——给wxuser设置id
 */

/**
 * 业务实现类：
 */
@Service
public class LogininfoServiceImpl extends BaseServiceImpl<Logininfo> implements ILogininfoService {
    @Autowired
    private LogininfoMapper logininfoMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private WxuserMapper wxuserMapper;
    @Autowired
    private UserMapper userMapper;
    /**
     * 后台账号登陆
     * @param loginDto
     * @return
     */
    @Override
    public Map<String, Object> loginAccount(LoginDto loginDto) {
        //1.空值校验
        if(StringUtils.isEmpty(loginDto.getAccount()) || StringUtils.isEmpty(loginDto.getCheckPass())){
            throw new BusinessException("后台：信息不能为空");
        }
        //2.账号校验
        Logininfo logininfo = logininfoMapper.findByAccount(loginDto);
        if(logininfo == null){
            throw new BusinessException("账号错误，请重新输入！");
        }
        //3.密码校验
        String isputMd5Pwd = Md5Utils.encrypByMd5(loginDto.getCheckPass() + logininfo.getSalt());
        if(!isputMd5Pwd.equals(logininfo.getPassword())){
            throw new BusinessException("密码错误，请重新输入！");
        }
        //4.状态校验
        if(!logininfo.getDisable()){
            throw new BusinessException("该账号被禁用，请联系管理员！");
        }
//        //5.存入redis：验证是否登陆；回显用户名
//        String token = UUID.randomUUID().toString();//36位随机字符串；含4个-
//        redisTemplate.opsForValue().set(token,logininfo,30, TimeUnit.MINUTES);
//        //6.返回数据
//        Map<String,Object> map = new HashMap<>();
//        map.put("token",token);
//        //安全考虑：返回前端之前将密码和盐值清空
//        logininfo.setPassword(null);
//        logininfo.setSalt(null);
//        map.put("logininfo",logininfo);

        //替换JWT方案
        return loginSuccessJwtHandler(logininfo);
    }

    /**
     * 微信扫码登陆【2】
     * @param map
     * @return
     */
    @Override
    public AjaxResult loginWechat(Map<String, String> map) {
        //一：设置code；获取2个参数
        //空值校验
        String code = map.get("code");
        if(StringUtils.isEmpty(code)){
            throw new BusinessException("亲，网络异常，请稍后再试！");
        }
        
        //1.获取请求参数,组装请求地址
        String url = WxConstants.GET_ACK_URL.replace("APPID", WxConstants.APPID)
                .replace("SECRET", WxConstants.SECRET)
                .replace("CODE", code);
        //2.发送请求:返回JSON对象
        String jsonStr = HttpUtil.httpGet(url);
        JSONObject jsonObj = JSONObject.parseObject(jsonStr);
        //获取openid
        String openid = jsonObj.getString("openid");
        //获取access_token
        String access_token = jsonObj.getString("access_token");
        //判断
        Wxuser wxuser = wxuserMapper.findByOpenid(openid);
        if(wxuser != null){//绑定过
            //注意：绑定过，但是没有user信息，照样跳转重新绑定【场景：绑定过，又注销了user；应该注销user时候同时注销Wxuser】
            User user = userMapper.loadById(wxuser.getUserId());//根据userId查询logininfo
            if(user != null){//注册了user
                //查找登陆信息，存入redis
                Logininfo logininfo = logininfoMapper.loadById(user.getLogininfoId());
//                //免密登陆
//                String token = UUID.randomUUID().toString();//36位随机字符串；含4个-
//                redisTemplate.opsForValue().set(token,logininfo,30, TimeUnit.MINUTES);
//                //6.返回数据
//                Map<String,Object> resultMap = new HashMap<>();
//                resultMap.put("token",token);
//                //安全考虑：返回前端之前将密码和盐值清空
//                logininfo.setPassword(null);
//                logininfo.setSalt(null);
//                resultMap.put("logininfo",logininfo);

                //替换JWT方案
                Map<String, Object> resultMap = loginSuccessJwtHandler(logininfo);
                return AjaxResult.me().setObj(resultMap);//绑定过，也注册过；响应前端登陆信息
            }
        }
        //【没有绑定过】:响应页面跳转地址参数——>发送手机验证码——>进行绑定
        System.out.println("?access_token="+access_token+"&openid="+openid);
        return AjaxResult.me().setSuccess(false).setObj("?access_token="+access_token+"&openid="+openid);

    }

    /**
     * 绑定微信登陆【没有绑定过微信——1.没有注册过;2.注册过；】
     * @param map
     * @return
     */
    @Override
    public AjaxResult wechatBinder(Map<String, String> map) {
        String phone = map.get("phone");
        String verifyCode = map.get("verifyCode");
        String accessToken = map.get("accessToken");
        String openId = map.get("openId");
        //1.空值校验
        if(StringUtils.isEmpty(phone) || StringUtils.isEmpty(verifyCode)){
            throw new BusinessException("亲，信息不能为空！");
        }
        //2.验证码校验：1.过期；2.正确
        Object obj = redisTemplate.opsForValue().get("binder:" + phone);
        if(obj == null){
            throw new BusinessException("亲，手机验证码已过期！");
        }
        if(!verifyCode.equals(obj.toString().split(":")[0])){
            throw new BusinessException("亲，手机验证码不正确！");
        }
        //3.组装url参数
        String url = WxConstants.GET_USER_URL.replace("ACCESS_TOKEN", accessToken)
                .replace("OPENID", openId);
        //4.获取用户微信信息[微信官方返回]-转换成Wxuser对象
        String jsonStr = HttpUtil.httpGet(url);
        Wxuser wxuser = jsonStr2WxUser(jsonStr);//此时wxuser的id为空；userId为空
        //5.判断：没绑定微信——是否注册账号【以前通过手机号码注册过没有绑定，可以根据手机号查询】
        User user = userMapper.findByPhone(phone);

        //5.1没有注册-注册user-
        if(user == null){
            //【1.phone2user】
            user = phone2User(phone);
            //【1.user2logininfo】
            Logininfo logininfo = user2Logininfo(user);
            //保存logininfo,产生自增id
            logininfoMapper.add(logininfo);
            //logininfo的id设置给user
            user.setLogininfoId(logininfo.getId());
            //保存user
            userMapper.add(user);
        }
        //5.2注册过-给Wxuser设置userId-绑定(保存wxuser)微信免密登陆
        wxuser.setUserId(user.getId());//此时wxuser有userId，id自增长得到
        wxuserMapper.add(wxuser);

        //6.获取user的logininfo存入redis，做登陆拦截
        Logininfo logininfo = logininfoMapper.loadById(user.getLogininfoId());
//        //7.将logininfo存入redis，做登陆拦截
//        String token = UUID.randomUUID().toString();//36位随机字符串；含4个-
//        redisTemplate.opsForValue().set(token,logininfo,30, TimeUnit.MINUTES);
//        //8.返回数据
//        Map<String,Object> resultMap = new HashMap<>();
//        resultMap.put("token",token);
//        //安全考虑：返回前端之前将密码和盐值清空
//        logininfo.setPassword(null);
//        logininfo.setSalt(null);
//        resultMap.put("logininfo",logininfo);

        //替换jwt方案
        Map<String, Object> resultMap = loginSuccessJwtHandler(logininfo);
        return AjaxResult.me().setObj(resultMap);
    }

    /**
     * 将user信息同步至logininfo
     * @param user
     * @return
     */
    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setDisable(true);
        logininfo.setType(1);
        return logininfo ;
    }

    /**
     * 首次绑定微信，根据电话注册user
     * @param phone
     * @return
     */
    private User phone2User(String phone) {
        User user = new User();
        user.setPhone(phone);
        user.setUsername(phone);
        user.setState(1);
        String salt = StrUtils.getComplexRandomString(32);
        String pwd = StrUtils.getComplexRandomString(12);
        String md5Pwd = Md5Utils.encrypByMd5(pwd + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);
        return user;
    }

    /**
     * 将微信用户信息转换成Wxuser
     * @param jsonStr
     * @return
     */
    private Wxuser jsonStr2WxUser(String jsonStr) {
        JSONObject obj = JSONObject.parseObject(jsonStr);
        Wxuser wxuser = new Wxuser();
        wxuser.setUnionid(obj.getString("unionid"));
        wxuser.setNickname(obj.getString("nickname"));
        wxuser.setOpenid(obj.getString("openid"));
        wxuser.setHeadimgurl(obj.getString("headimgurl"));
        return wxuser;
    }

    /**
     * 登陆成功：封装JWT方案操作登录信息
     * @return map
     */
    private Map<String,Object> loginSuccessJwtHandler(Logininfo logininfo){
        Map<String,Object> map = new HashMap<>();//向前端传值
        LoginData loginData = new LoginData();//JWT加密使用
        //1.设置登录信息
        logininfo.setSalt(null);
        logininfo.setPassword(null);
        map.put("logininfo",logininfo);
        loginData.setLogininfo(logininfo);
        //2.查询 菜单,权限  【只针对后台管理员做了权限】
        if(logininfo.getType() == 0){
            //设置权限
            List<String> permissions = logininfoMapper.findPermissionsByLogininfoId(logininfo.getId());
            map.put("permissions",permissions);
            loginData.setPermissions(permissions);
            //设置菜单
            List<Menu> menus = logininfoMapper.findMenusByLogininfoId(logininfo.getId());
            map.put("menus",menus);
            loginData.setMenus(menus);
        }
        //设置jwt token logininfo
        try {
            PrivateKey privateKey = RsaUtils.getPrivateKey(RsaUtils.class.getClassLoader().getResource("auth_rsa.pri").getFile());
            String jwtToken = JwtUtils.generateTokenExpireInMinutes(loginData, privateKey, 30);
            map.put("token",jwtToken);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }
}
